package com.pcbly.web.components.email;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;   

import com.pcbly.web.bean.mail.UserMailBean;
import com.pcbly.web.bean.mail.UserReceiveMainBean;

public class MailReceiveHotmail extends AbstractReceive { 
	
	public List<UserReceiveMainBean> receiveMail() throws Exception {
		List<UserReceiveMainBean> list = new ArrayList<UserReceiveMainBean>();
		Properties prop = new Properties(); 
		Session session = Session.getInstance(prop);
		Store store = session.getStore("davmail"); 
		String fromEmail=getFromEmail();
		System.out.println(fromEmail);
		store.connect(null,fromEmail,bean.getPassword());
		if (store.isConnected()) {
			Folder inbox = store.getFolder("INBOX");
			if (inbox.exists()) {
				inbox.open(Folder.READ_ONLY);
				Message[] messages = inbox.getMessages();
				int nCount = inbox.getMessageCount();
				System.out.println("Inbox contains " + nCount + " messages");
				for (Message message : messages) { 
					UserReceiveMainBean mainBean = new UserReceiveMainBean();
					mainBean.setTitle(getSubject(message));   
					mainBean.setFroms(getFrom(message));
					mainBean.setFromTos(getTo(message));
					mainBean.setFromCCs(getCc(message));
					mainBean.setFromBCCs(getBcc(message));
					mainBean.setReceiveDate(getSentDate(message));
					mainBean.setContent(getMailContent((Part) message)); 
					if (isContainAttach((Part) message)) {
						mainBean.setIsAttach(1);
						mainBean.setAttachPath(saveAttachMent((Part) message));
					} else {
						mainBean.setIsAttach(0);
					}
					list.add(mainBean);
				}
			}
		}
		return list;
	}
	public static void main(String[]args){
		MailReceiveHotmail receive=new MailReceiveHotmail();
		UserMailBean userMail=new UserMailBean();
		userMail.setUserName("pxjianke@hotmail.com");
		userMail.setPassword("tsgm23258759");
		receive.setBean(userMail); 
		try{
			receive.receiveMail();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
